package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 移动端拦截器
 */
@Slf4j
@Component
public class MobileInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenProperties jwtTokenProperties;

    /**
     * 预处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理器
     * @return boolean
     * @author YiSheep
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), jwt);
        Long id = Long.valueOf(claims.get("id").toString());
        if (ObjectUtil.isEmpty(id)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        log.info("会员id:{}",id);
        ThreadLocalUtil.set(id);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}